package wahadlo.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

import javax.swing.JComponent;

import wahadlo.model.Model;
import wahadlo.model.ModelRecipient;
import wahadlo.model.Point;

public class BobComponent extends JComponent implements ModelRecipient {

	private static final long serialVersionUID = 1L;

	private final Color bkg = Color.WHITE;
	private final Color twine = Color.BLACK;
	private Color ball = Color.RED;

	private final Dimension size = new Dimension(200, 400);
	private Graphics2D canvas;
	private Model model;
	private BufferedImage bufferedImage = null;

	@Override
	public void paint(Graphics g) {
		if (model == null) {
			bufferedImage = new BufferedImage(200, 400,
					BufferedImage.TYPE_3BYTE_BGR);
			canvas = bufferedImage.createGraphics();
			Dimension size = getSize();
			canvas.setColor(bkg);
			canvas.fillRect(0, 0, size.width, size.height);
			canvas.setColor(twine);
			canvas.drawLine(100, 0, 100, 300);
			canvas.setColor(ball);
			canvas.fillOval(90, 300, 20, 20);
		} else {
			drawModel();
		}
		g.drawImage(bufferedImage, 0, 0, null);
	}

	private void drawModel() {
		canvas.setColor(bkg);
		canvas.fillRect(0, 0, size.width, size.height);
		canvas.setColor(twine);
		canvas.drawLine(100, 0, 100, 300);
		canvas.setColor(ball);
		canvas.fillOval(90, 300, 20, 20);

		Double arcRad = Math.asin(((Point) model.getProperties().get("point"))
				.getY() / 500); // Double arc = 180*arcRad/Math.PI;

		AffineTransform affineTransform = new AffineTransform();
		affineTransform.rotate(arcRad, 0,100); // affineTransform.scale(10,10);
		canvas.rotate(arcRad);
	}

	public BobComponent() {
		setMinimumSize(size);
	}

	@Override
	public Dimension getMaximumSize() {
		return size;
	}

	@Override
	public Dimension getMinimumSize() {
		return size;
	}

	@Override
	public Dimension getPreferredSize() {
		return size;
	}

	public void setModel(Model model) {
		this.model = model;
		update();
	}

	/**
	 * metoda aktualizuje stan obiektu po otrzymaniu nowego modelu.
	 */
	private void update() {
		repaint();
	}

	/**
	 * Metoda usuwa dane z obiektu i przywraca jego pierwotny kształt.
	 */
	public void clean() {
		model = null;
		update();
	}
}
